package com.zhongxi.guoyuan.view;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.consume.ConsumeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.consumerYield.ConsumeData;
import com.zhongxi.guoyuan.entity.consumerYield.ConsumeDataResult;
import com.zhongxi.guoyuan.entity.consumerYield.Summary;
import com.zhongxi.guoyuan.entity.consumerYield.ToAppleyWithDraw;
import com.zhongxi.guoyuan.entity.consumerYield.TodayConsumerYield;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.view.personalCenter.WithDrawCashActivity;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class ConsumerLoveYieldActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<ListView>, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.consume_yesterday_time)
    TextView consumeYesterdayTime;
    @Bind(R.id.consume_yesterday_number)
    TextView consumeYesterdayNumber;
    @Bind(R.id.consume_no_earn)
    TextView consumeNoEarn;
    @Bind(R.id.consume_has_Earn)
    TextView consumeHasEarn;
    @Bind(R.id.consume_activity_hasearn)
    TextView consumeActivityHasearn;
    @Bind(R.id.consume_allEarn_num)
    TextView consumeAllEarnNum;
    @Bind(R.id.consume_withdraw_num)
    TextView consumeWithdrawNum;
    @Bind(R.id.consume_tv_withdraw)
    TextView consumeTvWithdraw;
    @Bind(R.id.consume_hold_num)
    TextView consumeHoldNum;
    @Bind(R.id.consume_tv_applywithdraw)
    TextView consumeTvApplywithdraw;
    @Bind(R.id.consume_activity_moregive)
    TextView consumeMoreGive;//消费多增红豆
    private String type;
    @Bind(R.id.swipRefreshlayout)
    SwipeRefreshLayout swipRefreshlayout;
    @Bind(R.id.consume_exchange_gains)
    TextView consumeExchangeGains;


    private PullToRefreshListView listview;


    private ConsumeAdapter adapter;
    private List<ConsumeData> data = new ArrayList<>();

    private String floatinggains = "0";
    private String fixedgains = "0";
    private String totalamount = "0";

    //已提现
    private String withdrawals = "0";
    //赠送用户红豆数
    private String givegains = "0";
    //活动推广收益
    private String sharegains = "0";
    //线上超市 美豆区 %5 返红
    private String fivepercentredgains;
    //线下超市 支付 返红豆 %3
    private String offlinegains;
    //消费支出红豆
    private String paygains;

    //豆豆兑换
    private String exchangegains;


    //消费已收益
    private String consumeEarned = "";
    //待收益红豆
    private String noConsumeEarned = "";
    //总收益（消费已收益 + 活动已收益 + 消费即刻送 + 系统赠送+线下商家即刻送）
    private String allConsumeEarend = "";
    //现存红豆（总收益-已提现）
    private String nowHold = "";


    private String trim;
    private int mEntryto;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.fragment_consumer_love_yield);
        ButterKnife.bind(this);
        initTitle();
        tvTitle.setText("昨日现金收益");
        listview = (PullToRefreshListView) findViewById(R.id.yesterday_listview_record);
        listview.setMode(PullToRefreshBase.Mode.BOTH);
        if (getIntent() != null) {
            mEntryto = getIntent().getIntExtra("entryto", 0);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new ConsumeAdapter(context);
        listview.setAdapter(adapter);
        consumeYesterdayTime.setText("昨日" + CommonTool.formatYesterday());
        getTodayYield();
    }

    private void getTodayYield() {
        type = "today";
        getServer(Url.CONSUMER_TODAY_YIELD, null, "", false, null, "get");
    }


    /**
     * 收益明细
     */
    private void getConsumeList() {
        type = "consumelist";
        String str = "&page=" + pageNum;
        getServer(Url.CONSUME_LIST, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        listview.setOnRefreshListener(this);
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (data.size() == 0) {
                    swipRefreshlayout.setEnabled(true);
                } else {
                    swipRefreshlayout.setEnabled(false);
                }
            }
        });
        swipRefreshlayout.setOnRefreshListener(this);
    }

    private void toAppleyDialog() {
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_to_appley, null);
        final ImageView post_nopay_ivCancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        TextView no_withdraw = (TextView) view.findViewById(R.id.no_withdraw);
        final EditText post_nopay_pwd = (EditText) view.findViewById(R.id.post_nopay_pwd);
        TextView post_nopay_tvSure = (TextView) view.findViewById(R.id.post_nopay_tvSure);
        dialog.setView(view);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        post_nopay_ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        if (nowHold != null) {
            no_withdraw.setText("您当前拥有" + DataUtil.formatData(nowHold) + "元");
        } else {
            no_withdraw.setText("您当前拥有0元");
        }

        post_nopay_tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                trim = post_nopay_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    showShortToast("请输入提现金额");
                } else if (!CommonTool.isNumeric(trim)) {
                    showShortToast("请输入正确的数字");

                } else if (!CommonTool.sub(nowHold, "50.00")) {
                    showShortToast("抱歉,您的余额不足以提现!");

                } else if (!CommonTool.sub(trim, "50.00") || Integer.parseInt(trim) % 10 != 0) {
                    Toast.makeText(context, "请输入大于50且是10的倍数的金额", Toast.LENGTH_LONG).show();

                } else if (CommonTool.sub2(trim, nowHold)) {
                    showShortToast("您输入的数量超出了您的未提现金额");
                } else if (TextUtils.isEmpty(MyApplication.getInstance().getAppOpenid())) {
                    ToastUtil.show("您还没有微信授权登录,暂不能体现!");
                } else {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("amount", MyApplication.getInstance().descsc(trim));
                    type = "witchdraw";
                    getServer(Url.USER_TOAPPLEY_WITHDRAW, map, "", false, null, "post");
                    dialog.dismiss();
                }
            }
        });


    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        swipRefreshlayout.setRefreshing(false);
        if ("today".equals(type)) {
            TodayConsumerYield todayConsumerYield = gson.fromJson(response, TodayConsumerYield.class);
            MyApplication.getInstance().setSpValue(todayConsumerYield.getSafeobj());

            if (todayConsumerYield.getUserSummary() != null && !"".equals(todayConsumerYield.getUserSummary())) {
                Summary summary = todayConsumerYield.getUserSummary();
                if (summary.getTotalamount() != null && !"".equals(summary.getTotalamount())) {
                    totalamount = summary.getTotalamount();
                } else {
                    totalamount = "0";
                }
                if (summary.getFloatinggains() != null && !"".equals(summary.getFloatinggains())) {
                    floatinggains = summary.getFloatinggains();
                } else {
                    floatinggains = "0";
                }
                if (summary.getFixedgains() != null && !"".equals(summary.getFixedgains())) {
                    fixedgains = summary.getFixedgains();
                } else {
                    fixedgains = "0";
                }

                if (null != summary.getGivegains() && !"".equals(summary.getGivegains())) {
                    givegains = summary.getGivegains();
                } else {
                    givegains = "0";
                }
                if (null != summary.getSharegains() && !"".equals(summary.getSharegains())) {
                    sharegains = summary.getSharegains();
                } else {
                    sharegains = "0";
                }
                if (null != summary.getFivepercentredgains() && !"".equals(summary.getFivepercentredgains())) {
                    fivepercentredgains = summary.getFivepercentredgains();
                } else {
                    fivepercentredgains = "0";
                }
                if (null != summary.getOfflinegains() && !"".equals(summary.getOfflinegains())) {
                    offlinegains = summary.getOfflinegains();
                } else {
                    offlinegains = "0";
                }
                if (summary.getWithdrawals() != null && !"".equals(summary.getWithdrawals())) {
                    withdrawals = summary.getWithdrawals();
                } else {
                    withdrawals = "0";
                }

                if (null != summary.getPaygains() && !"".equals(summary.getPaygains())) {
                    paygains = summary.getPaygains();
                } else {
                    paygains = "0";
                }

                if (null != summary.getExchangegains() && !"".equals(summary.getExchangegains())) {
                    exchangegains = summary.getExchangegains();
                } else {
                    exchangegains = "0";
                }

            }

            initInfo(todayConsumerYield);

            getConsumeList();

        } else if ("witchdraw".equals(type)) {
            ToAppleyWithDraw toAppleyWithDraw = gson.fromJson(response, ToAppleyWithDraw.class);
            MyApplication.getInstance().setSpValue(toAppleyWithDraw.getSafeobj());
            showApplySuccessDialog();
            getTodayYield();
        } else if ("consumelist".equals(type)) {

            //收益明细
            ConsumeDataResult consumeDataResult = gson.fromJson(response, ConsumeDataResult.class);
            MyApplication.getInstance().setSpValue(consumeDataResult.getSafeobj());
            if (pageNum == 1) {
                data.clear();
            }
            listview.onRefreshComplete();
            if (consumeDataResult.getData().size() > 0) {

                data.addAll(consumeDataResult.getData());
                adapter.setList(data);
            }

        }
    }

    private void showApplySuccessDialog() {
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        View mView = LayoutInflater.from(this).inflate(R.layout.dialog_apply_tip, null);
        TextView withdraw = (TextView) mView.findViewById(R.id.withdraw_assistant);
        TextView know = (TextView) mView.findViewById(R.id.btn_know);
        dialog.setView(mView);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
        withdraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(WithDrawCashActivity.class);
            }
        });
        know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });

    }

    private void initInfo(TodayConsumerYield todayConsumerYield) {
        //消费已收益=====》已分期奖励红豆
        consumeEarned = DataUtil.formatDataSixPoint(DataUtil.add(floatinggains, fixedgains));
        //待收益
        noConsumeEarned = DataUtil.formatDataSixPoint(DataUtil.subtract(totalamount, consumeEarned));
        //活动已收益====》组团获得红豆
        sharegains = DataUtil.formatDataSixPoint(sharegains);
        //线下消费红包
        offlinegains = DataUtil.formatDataSixPoint(offlinegains);
        //豆豆兑换
        exchangegains = CommonTool.getWhole(exchangegains);
        //总已收益红豆
        allConsumeEarend = DataUtil.add(consumeEarned, sharegains);
        allConsumeEarend = DataUtil.add(allConsumeEarend, exchangegains);
        allConsumeEarend = DataUtil.add(allConsumeEarend, givegains);
        allConsumeEarend = DataUtil.formatDataSixPoint(DataUtil.add(allConsumeEarend, offlinegains));
        //已经体现收益
        withdrawals = DataUtil.formatDataSixPoint(withdrawals);
        //现存红豆
        nowHold = DataUtil.subtract(allConsumeEarend, withdrawals);
        nowHold = DataUtil.formatDataSixPoint(DataUtil.subtract(nowHold, paygains));

        consumeHasEarn.setText(consumeEarned + "元");
        consumeActivityHasearn.setText(sharegains + "元");
        consumeMoreGive.setText(offlinegains + "元");
        consumeAllEarnNum.setText(allConsumeEarend + "元");
        consumeWithdrawNum.setText("已经提现收益：" + withdrawals + "元");
        consumeHoldNum.setText("当前拥有余额：" + nowHold + "元");
        consumeExchangeGains.setText(exchangegains + " 元");
        //待分期奖励红豆
        consumeNoEarn.setText(noConsumeEarned + "元");
        if (null != todayConsumerYield.getPrevDayGains() && !"".equals(todayConsumerYield.getPrevDayGains())) {
            consumeYesterdayNumber.setText(DataUtil.formatDataSixPoint(todayConsumerYield.getPrevDayGains()) + "元");
        } else {
            consumeYesterdayNumber.setText(getString(R.string.sixZero, "元"));
        }

    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(result.getSafeobj());
        if (result.getCode() == 1000) {

            if (null != trim && !"".equals(trim)) {
                if (Integer.parseInt(trim) > 50 && Integer.parseInt(trim) % 10 != 0) {
                    showShortToast("请输入大于50且是10的整数倍的值");
                }
            }
        } else if (result.getCode() == 1001) {
            showShortToast("用户未登录");
        } else if (result.getCode() == 1106) {
            showShortToast("用户消费分红不足");
        } else if (result.getCode() == 1666) {
            showShortToast("服务暂不可用， 请稍后重试");
        } else if (result.getCode() == 1005) {
            ToastUtil.show("老用户,未经过 app 微信用户授权");
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getConsumeList();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getConsumeList();
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (1 == mEntryto) {
            startAct(MainHomeActivity.class);
        }

    }

    @OnClick({R.id.ivBack, R.id.consume_tv_withdraw, R.id.consume_tv_applywithdraw})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                if (1 == mEntryto) {
                    startAct(MainHomeActivity.class);
                }
                break;
            case R.id.consume_tv_withdraw:
                startAct(WithDrawCashActivity.class);
                break;
            case R.id.consume_tv_applywithdraw:
                toAppleyDialog();
                break;
        }
    }

    @Override
    public void onRefresh() {
        getTodayYield();
    }
}
